<template>
	<el-container>
		<el-aside width="300px" style="background-color: #fff;">
			<!--			左边用户-->
			<el-row class="sticky-top">
				<el-header class="side-head">
					<h2>候诊中心</h2>
					<el-row class="bench-stat">
						<el-text class="text0">工作状态</el-text>
						<el-switch
							v-model="stat_switch"
							class="mb-2"
							style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949; margin-right: 15px; "
							inline-prompt
							active-text="出诊"
							inactive-text="停诊"
							@change="changeSwitch"
							:disabled="stat != 0"
						/>
						<template v-if="stat_switch">
							<el-text class="text1">接诊状态</el-text>
							<el-text class="text2" :class="{dark: doctor_info.job_status != 2}">
								{{ doctor_info.job_status_name }}
							</el-text>
						</template>
					</el-row>
				</el-header>
			</el-row>
			<el-container class="waiting-users" direction="vertical">
				<el-row class="list" direction="vertical">
					<el-col :span="24" v-for="(item, index) in patient_order_list" v-bind:key="index">
						<el-container class="box-card">
							<el-row class="user-row" @click="selectPatientOrder(item)" :data-id="item.patient_sn">
								<el-col :span="22" class="user-met">
									<el-text class="name">{{ item.patient_name }}</el-text>
									<img class="sex-icon" :src="item.patient_sex == 1 ? 'img/man.png' : 'img/fem.png'"/>
									<el-text class="sex">{{ item.patient_sex_name }}</el-text>
									<el-text>{{ item.patient_age }}</el-text>
								</el-col>
								<el-col :span="2">
									<div class="user-num">{{ item.patient_number }}</div>
								</el-col>
							</el-row>
						</el-container>
					</el-col>
				</el-row>
			</el-container>
		</el-aside>

		<!--		中间区域-->
		<el-row class="bench-body">
			<el-col :span="24">
				<div class="grid-content ep-bg-purple"/>
				<el-container class="bench-content" direction="vertical">
					<el-row class="bench-main">
						<el-col :span="24" class="answer" v-if="stat === 0 || doctor_info.work_status != 1">
							<el-text class="mx-1" size="large" style="font-weight: bold;">暂无数据</el-text>
						</el-col>
						<el-col :span="24" class="answer" v-if="stat === 1 && doctor_info.work_status == 1">
							<el-text class="mx-1" size="large">患者发起视频通话，等待接听...</el-text>
						</el-col>
						<el-col :span="24" class="video" :class="{ringOff: ring_off}"
								v-if="stat === 2 && doctor_info.work_status == 1">
							<div v-if="!ring_off" id="videoWrap">
							</div>
							<div class="ring-off-text" v-else>
								<el-button type="success" :loading="is_stop_1" @click="stopPatient(1)">完成问诊并继续接诊
								</el-button>
								<el-button text :loading="is_stop_2" @click="stopPatient(0)">完成问诊，停止接诊</el-button>
							</div>
						</el-col>
						<div class="bench-doctorVideoWrap" id="benchDoctorVideoWrap" v-if="stat === 2 && doctor_info.work_status == 1 && !ring_off">
						</div>
					</el-row>
					<el-row class="bench-bott" v-if="stat !== 0 && doctor_info.work_status == 1">
						<el-col :span="24" class="answer" v-if="stat === 1">
							<el-container direction="vertical" @click="answerCall">
								<el-icon :size="68" style="margin-bottom: 10px;">
									<a href="javascript:;"><img src="img/answer.png"
																style="width:68px;height:68px;"/></a>
								</el-icon>
								<el-button type="primary" link>接听</el-button>
							</el-container>
						</el-col>
						<el-col :span="24" class="video-act" v-if="stat === 2 && !ring_off">
							<el-button link style="color: #00D8D4;" @click="stopVolume" v-if="false">静音</el-button>
							<el-text style="color:#999999;">通话中{{ time_up }}</el-text>
							<el-button link type="danger" @click="ringOff">通话结束</el-button>
						</el-col>
					</el-row>
				</el-container>
			</el-col>
		</el-row>

		<!--		右边区域-->
		<el-aside width="460px" style="background-color: #fff; position: relative; "
				  v-if="stat !== 0 && doctor_info.work_status == 1">
			<el-container class="bench-side">


				<el-row v-if="patient_pic_list.length > 0">
						<el-alert title="用户已上传病历，点击查看" type="warning" show-icon :closable="false" style="margin-bottom: 15px;"/>
						<div class="demo-image__preview">
							<el-image
								style="width: 100px; height: 100px"
								:src="patient_pic"
								:zoom-rate="1.2"
								:max-scale="7"
								:min-scale="0.2"
								:preview-src-list="patient_pic_list"
								:initial-index="patient_pic_list.length"
								@switch="switchPic"
								@show="showPic"
								@close="closePic"
								fit="cover"
							/>
							<div class="image-info" v-if=" show_patient_pic_num "> {{ patient_pic_index }} / {{ patient_pic_list.length }} </div>
						</div>
				</el-row>


				<el-row class="bench-side-user">
					<header>
						<div class="head-item">
							<el-text style="margin-right: 5px;">姓名</el-text>
							<el-text>{{ patient_order.patient_name }}</el-text>
						</div>
						<div class="head-item">
							<el-text style="margin-right: 5px;">性别</el-text>
							<el-text>{{ patient_order.patient_sex_name }}</el-text>
						</div>
						<div class="head-item">
							<el-text style="margin-right: 5px;">出生日期</el-text>
							<el-text>{{ patient_order.patient_birthday }}</el-text>
						</div>
						<div class="head-item">
							<el-text style="margin-right: 5px;">证件号码</el-text>
							<el-text>{{ patient_order.patient_id_card }}</el-text>
						</div>
					</header>
					<el-container class="bench-side-user-dec">
						<el-row class="head-table">
							<el-col class="head-label">病情描述</el-col>
							<el-col class="head-con">
								{{ patient_order.illness_desc }}
							</el-col>
						</el-row>
						<el-row class="head-table">
							<el-col class="head-label">持续时间</el-col>
							<el-col class="head-con">
								{{ patient_order.duration }}
							</el-col>
						</el-row>
					</el-container>
				</el-row>
				<el-row v-if="stat === 2 && doctor_info.work_status == 1">
					<el-container class="bench-side-action">
						<el-tabs v-model="actionName" class="side-tabs">
							<el-tab-pane label="病例" name="first">
								<table>
									<tr>
										<td valign="top">主诉</td>
										<td>
											<el-input :rows="2" type="textarea" placeholder=""
													  v-model="principal_action"/>
										</td>
									</tr>
									<tr>
										<td valign="top">现病史</td>
										<td>
											<el-input placeholder="" v-model="medical_history"/>
										</td>
									</tr>
									<tr>
										<td valign="top">既往病史</td>
										<td>
											<el-input placeholder="" v-model="anamnesis"/>
										</td>
									</tr>
									<tr>
										<td valign="top">过敏史</td>
										<td>
											<el-input placeholder="" v-model="allergy"/>
										</td>
									</tr>
									<tr>
										<td valign="top">拟诊</td>
										<td>
											<el-input placeholder="" v-model="pseudodiagnosis"/>
										</td>
									</tr>
									<tr>
										<td valign="top">诊疗建议</td>
										<td>
											<el-input type="textarea" placeholder="" v-model="patient_suggest"/>
										</td>
									</tr>
								</table>
								<div class="save-row-height"></div>
							</el-tab-pane>
							<el-tab-pane label="用药建议" name="second">
								<el-row class="advise-head">
									<el-text>请为患者添加用药建议</el-text>
									<el-button type="primary" link @click="addMed">+添加药品</el-button>
								</el-row>
								<el-row class="advise-body">
									<el-col :size="24" class="advise-body-item"
											v-for="(med, med_idx) in medicine_advise" v-bind:key="med">
										<a href="javascript:;" class="del-act" @click="delMed(med_idx)"><img
											src="img/del.png"/></a>
										<div class="advise-body-in">
											<div class="advise-body-in-head">
												<el-text class="advise-med">{{ med.medicine_name }}</el-text>
												<el-text>{{ med.sku }}</el-text>
											</div>
											<el-input class="advise-body-inp" placeholder="请输入药品数量"
													  v-model="med.medicine_num"/>
										</div>
										<div class="advise-body-desc">
											<el-input :rows="2" type="textarea" placeholder="请输入用法用量"
													  v-model="med.use_desc"/>
										</div>
									</el-col>
								</el-row>
								<div class="save-row-height"></div>
							</el-tab-pane>
						</el-tabs>
					</el-container>
				</el-row>
			</el-container>
			<el-row class="save-row">
				<el-button type="primary" size="large" :loading="isSaveing" @click="save">保存</el-button>
			</el-row>
		</el-aside>
	</el-container>
	<save-dialog v-if="dialog.save" ref="saveDialog" @success="handleSuccess" @closed="dialog.save=false"></save-dialog>
	<el-dialog v-model="centerDialogVisible" title="提醒" width="30%" center>
		<span>您长时间无操作，您已自动下线。</span>
		<template #footer>
		  <span class="dialog-footer">
			<el-button type="primary" @click="autoUp">
			  确定
			</el-button>
		  </span>
		</template>
	</el-dialog>
</template>

<script>
import saveDialog from './save.vue'
import RTC_DATA from "@/views/doctor/rtc_data";
import RTC_UI from "@/views/doctor/rtc_ui";
import tool from '@/utils/tool';
import {ElNotification} from 'element-plus'
import {h} from 'vue'

const unloadHandler = (e) => {
	e.preventDefault();
	e.returnValue = true;
}

export default {
	emits: ['success', 'closed'],
	components: {
		saveDialog
	},
	watch: {
		stat: function (newStat) {
			console.log('stat changed to ' + newStat);
			if (newStat === 0) {
				tool.cookie.remove('in_process');
				window.removeEventListener('beforeunload', unloadHandler);
			} else {
				tool.cookie.set('in_process', 1);
				window.addEventListener('beforeunload', unloadHandler);
			}
		}
	},
	data() {
		return {
			debug: false,
			mode: 'add',
			stat: 0, // 工作状态：0停诊 1接诊电话coming 2接诊
			ring_off: false, // 是否通话结束
			stat_switch: false,
			is_stop_1: false,
			is_stop_2: false,
			actionName: 'first',
			dialog: {
				save: false
			},
			silent: false,
			ws: null,
			rtc_ui: null,
			rtc_obj: null,
			channel_id: '',
			patient_id: 0,
			patient_sn: '',
			patient_order: {},
			patient_order_list: [],
			doctor_info: {},
			total_seconds: 0,
			time_up: '00:00',
			medicine_advise: [],
			isSaveing: false,
			principal_action: '',
			medical_history: '',
			anamnesis: '',
			allergy: '',
			pseudodiagnosis: '',
			patient_suggest: '',
			centerDialogVisible: false,
			is_calling: false,
			//问诊图片
			patient_pic:'',
			patient_pic_list:[],
			patient_pic_index:0,
			show_patient_pic_num:false
		}
	},
	mounted() {
		tool.cookie.remove('in_process');
		let u = new URL(location)
		let pro_url = u.hostname + '/wss';
		let is_production = process.env.NODE_ENV === 'production';
		let ws_api = `wss://${is_production ? pro_url : 'healthweb.ezhangxiu.cn'}/wss`;
		console.log('ws_api:', ws_api);
		if (this.debug) ws_api = 'wss://test.ezhangxiu.cn/testwss';
		this.ws = new WebSocket(ws_api);
		this.ws.onopen = () => {
			this.startPing();
		};

		this.ws.onmessage = (e) => {
			let data = JSON.parse(e.data),
				client_id = data.client_id || '';
			if (e.data && data.type !== 'pong') {
				console.log('msg', e.data);
			}
			if (data.type === 'init') {
				console.log('init client:', client_id);
				this.setOnline(client_id);
			} else if (data.type === 'call') {
				let rtc = data.rtc,
					patient = data.patient,
					channel_id = rtc.channel_id,
					patient_id = patient.patient_id,
					ins = false, append = false;
				if (this.stat === 0) {
					ins = true;
				} else if (this.patient_sn && patient.patient_sn !== this.patient_sn) {
					append = true;
				}
				if (ins) {
					this.channel_id = channel_id;
					this.patient_id = patient_id;
					this.patient_sn = patient.patient_sn;
					this.stat = 1;
					this.loadPatientOrder();
					this.loadDoctorInfo();
					this.loadPatientPic(this.patient_sn);
				}
				if (append) {
					this.appendToPatientOrder(patient.patient_sn);

				}
			} else if (data.type === 'broadcast') {
				let patient = data.patient,
					patient_sn = patient.patient_sn;
				this.appendToPatientOrder(patient_sn);
			} else if (data.type === 'broadcast_cancel') {
				let patient = data.patient,
					patient_sn = patient.patient_sn;
				this.removeFromPatientOrderList(patient_sn);
			} else if (data.type === 'ringoff') { // 用户挂断电话
				let patient = data.patient,
					patient_sn = patient.patient_sn,
					patient_order = data.patient_order || {},
					st_value = parseInt(patient_order.st_value) || 0,
					exp = parseInt(patient_order.exp) || 0;
				if (patient_sn !== this.patient_sn) return;
				if (st_value === 1) {
					setTimeout(() => {
						this.$API['doctor.bench'].status.post({type: ''}).then((res) => {
							console.log('Res:status', res);
							if (res.code !== 0) {
								this.$alert('status:' + res.message, "提示", {type: 'error'});
							} else {
								this.doctor_info = res.data;
								this.stat_switch = res.data.work_status == 1;
							}
						});
					}, 1000);
					ElNotification({
						title: '提示',
						message: h('b', {style: 'color: black'}, exp === 1 ? '异常挂断' : '用户挂断了'),
					});
				}
				if (this.stat === 1) {
					this.stat = 0;
					this.pateint_id = 0;
					this.patient_sn = '';
					this.mute(true);
				} else if (this.stat === 2) {
					if (this.ring_off) return;
					this.ringOff();
				}
			} else if (data.type === 'ppic_back') {
				// var pic_url = data.pic_url;
				// var copy = this.patient_pic_list.slice();
				// copy.push(pic_url);
				// this.patient_pic_list = copy;
				this.loadPatientPic(data.patient_sn);
				// console.log('ppic_back...', data);
			} else if (data.online === 0) {
				this.centerDialogVisible = true;
			}
		};
		this.ws.onclose = () => {
			this.centerDialogVisible = true;
		};
		this.ws.onerror = () => {
			this.centerDialogVisible = true;
		};
		this.rtc_ui = new RTC_UI(this);
		this.rtc_obj = new RTC_DATA();

		this.loadDoctorInfo();
		this.loadPatientOrderList();
		this.loadUnCompletePatientOrder();
		this.startQuery();
	},
	unmounted() {
		console.log('unmounted unmounted unmounted');
		if (this.rtc_obj) {
			this.mute(true);
			this.rtc_obj.unload();
		}
	},
	methods: {
		addMed() {
			this.dialog.save = true;
			this.$nextTick(() => {
				this.$refs.saveDialog.open(this.mode)
			})
		},
		//本地更新数据
		handleSuccess(medicine_list) {
			medicine_list.forEach(item => {
				let has = this.medicine_advise.filter(a => a.approve_code === item.approve_code).length > 0;
				if (!has) {
					this.medicine_advise.push({
						medicine_id: item.medicine_id,
						medicine_name: item.medicine_name,
						medicine_num: 1,
						approve_code: item.approve_code,
						use_desc: '',
						sku: item.guige,
					})
				}
			})
		},
		setOnline(client_id) {
			this.$API['doctor.bench'].status.post({type: 'online', client_id}).then((res) => {
				console.log('Res:online', res);
				if (res.code !== 0) {
					this.$alert('setOnline:' + res.message, "提示", {type: 'error'});
				}
			}).catch((msg) => {
				this.$alert(msg, "提示", {type: 'error'})
			})
		},
		answerCall() {
			if (this.is_calling) {
				return;
			}
			this.is_calling = true;
			this.$API['doctor.bench'].call.post({
				patient_sn: this.patient_sn,
				channel_id: this.channel_id
			}).then((res) => {
				console.log('Res:call', res);
				this.is_calling = false;
				if (res.code !== 0) {
					this.$alert('doctorCall:' + res.message, "提示", {type: 'error'});
				} else {
					console.log("call", res);
					this.stat = 2;
					this.startTime();
					this.loadDoctorInfo();
					this.loadPatientOrder();
					this.$nextTick(() => {
						let channel = res.data.channel;
						this.rtc_obj.unload();
						this.rtc_obj.init();
						this.rtc_obj.setChannel(channel, this.rtc_ui);
					});
				}
			}).catch((msg) => {
				this.is_calling =false;
				this.$alert(msg, "提示", {type: 'error'})
			});
		},
		loadPatientOrder() {
			if (!this.patient_id || !this.patient_sn) return;
			this.$API['patient.patient_order'].detail.post({patient_sn: this.patient_sn}).then((res) => {
				console.log('Res:patient order detail', res);
				if (res.code !== 0) {
					this.$alert('loadPatientOrder:' + res.message, "提示", {type: 'error'});
				} else {
					this.patient_order = res.data;
					this.principal_action = res.data.principal_action;
					this.medical_history = res.data.medical_history;
					this.anamnesis = res.data.anamnesis;
					this.allergy = res.data.allergy;
					this.pseudodiagnosis = res.data.pseudodiagnosis;
					this.patient_suggest = res.data.patient_suggest;
					this.medicine_advise = res.data.medicine_list.map(item => {
						item.sku = item.medicine_sku;
						return item;
					});
				}
			})
		},
		loadDoctorInfo() {
			this.$API['doctor.bench'].status.post({}).then((res) => {
				console.log('Res:status', res);
				if (res.code !== 0) {
					this.$alert('loadPatientOrderList:' + res.message, "提示", {type: 'error'});
				} else {
					this.doctor_info = res.data;
					this.stat_switch = res.data.work_status == 1 ? true : false;
				}
			})
		},
		loadPatientOrderList() {
			this.$API['patient.patient_order'].index.get({is_wait: 1, page_size: 100, doctor_id: 0, channel_provider: 'ZHIYING'}).then((res) => {
				if (res.code !== 0) {
					this.$alert('loadPatientOrderList:' + res.message, "提示", {type: 'error'});
				} else {
					this.patient_order_list = res.data.list;
				}
			});
		},
		loadUnCompletePatientOrder() {
			this.$API['doctor.bench'].un_complete.post({}).then((res) => {
				console.log('Res:un_complete', res);
				if (res.code !== 0) {
					ElNotification({
						title: '提示',
						message: h('b', {style: 'color: black'}, res.msg),
					});
				} else {
					let patient = res.data,
						// channel = patient.channel || {},
						patient_id = patient['patient_id'] || 0,
						patient_sn = patient['patient_sn'] || '';
					if (patient_sn !== '') {
						this.patient_id = patient_id;
						this.patient_sn = patient_sn;
						this.stat = 1;
						// if (!channel.channel_id) {
						// 	this.ringOff();
						// }
						this.loadPatientOrder();
						this.loadDoctorInfo();
						this.removeFromPatientOrderList(patient_sn);
						this.loadPatientPic(patient_sn);
						// if (channel.channel_id) {
						// 	this.$nextTick(() => {
						// 		this.rtc_obj.init();
						// 		this.rtc_obj.setChannel(channel, this.rtc_ui);
						// 	});
						// }
					}
				}
			})
		},
		changeSwitch() {
			this.$API['doctor.bench'].status.post({type: 'status'}).then((res) => {
				console.log('Res:status changeSwitch', res);
				if (res.code !== 0) {
					this.$alert('loadPatientOrderList:' + res.message, "提示", {type: 'error'});
				} else {
					this.doctor_info = res.data.doctor_info;
				}
			});
			if (this.stat_switch) { // 加载问诊单
				ElNotification({
					title: '提示',
					message: h('b', {style: 'color: black'}, '自动为您派单'),
				});
				this.loadPatientOrderList();
				this.$nextTick(() => {
					this.$API['doctor.bench'].assign_patient.post().then((res) => {
						console.log('Res:assign_patient', res);
						if (res.code !== 0) {
							ElNotification({
								title: '提示',
								message: h('b', {style: 'color: black'}, res.msg),
							})
						} else {
							this.patient_id = res.data.patient_id;
							this.patient_sn = res.data.patient_sn;
							this.stat = 1;
							this.loadPatientOrder();
							this.removeFromPatientOrderList(res.data.patient_sn);
						}
					}).catch((msg) => {
						ElNotification({
							title: '提示',
							message: h('b', {style: 'color: black'}, msg),
						})
					})
				});
			}
		},
		mute(val) {
			if (!this.rtc_obj) return;
			this.rtc_obj.muteCamera(val);
			this.rtc_obj.muteAudio(val);
		},
		startTime() {
			if (this.timer) {
				clearInterval(this.timer);
				this.total_seconds = 0;
				this.time_up = '00:00';
			}
			let pad = (value) => value > 9 ? value : '0' + value;
			this.timer = setInterval(() => {
				this.total_seconds += 1;
				let hour = Math.floor(this.total_seconds / 3600);
				let minute = Math.floor((this.total_seconds - hour * 3600) / 60);
				let second = this.total_seconds - (hour * 3600 + minute * 60);
				let total_minutes = hour * 60 + minute;
				this.time_up = pad(parseInt(total_minutes)) + ':' + pad(second);
			}, 1000);
		},
		ringOff() {
			if (this.timer) {
				clearInterval(this.timer);
				this.time_up = '00:00';
			}
			this.ring_off = true;
			this.mute(true);
			this.rtc_obj.unload();
		},
		stopVolume() {
			this.silent = !this.silent;
			this.rtc_obj.setSilent(this.silent);
		},
		delMed(index) {
			this.medicine_advise.splice(index, 1);
		},
		selectPatientOrder(row) {
			if (this.stat === 2) {
				this.$message.success("正在接诊中");
				return;
			}
			if (this.patient_sn === row.patient_sn) return;
			if (!this.stat_switch) {
				this.$confirm(`注：当前工作状态: 停诊`, '确认接诊后，将进入接诊模式', {
					type: 'warning',
					confirmButtonText: '确认接单',
					confirmButtonClass: 'el-button--danger'
				}).then(() => {
					this.$API['doctor.bench'].status.post({type: 'status'}).then((res) => {
						console.log('Res:status', res);
						if (res.code !== 0) {
							this.$alert('status:' + res.message, "提示", {type: 'error'});
						} else {
							this.doctor_info = res.data.doctor_info;
							this.stat_switch = res.data.doctor_info.work_status == 1;
							this.assign(row);
						}
					});
				});
			} else {
				this.assign(row);
			}
		},
		assign (row) {
			this.$API['doctor.bench'].assign_doctor.post({
				patient_sn: row.patient_sn,
			}).then((res) => {
				console.log('Res:assign_doctor', res);
				if (res.code !== 0) {
					this.$alert('save:' + res.message, "提示", {type: 'error'});
				} else {
					this.removeFromPatientOrderList(row.patient_sn);
					this.stat = 2;
					this.patient_id = row.patient_id;
					this.patient_sn = row.patient_sn;
					this.patient_order = {
						patient_name: row.patient_name,
						patient_sex_name: row.patient_sex_name,
						patient_age: row.patient_age,
						illness_desc: row.illness_desc,
					}
					this.loadPatientOrder();
					this.startTime();
					this.$nextTick(() => {
						let channel = res.data.channel;
						this.mute(true);
						this.rtc_obj.unload();
						this.rtc_obj.init();
						this.rtc_obj.setChannel(channel, this.rtc_ui);
						this.loadDoctorInfo();
					});
					//加载问诊图片
					this.loadPatientPic(this.patient_sn);
				}
			}).catch((msg) => {
				ElNotification({
					title: '提示',
					message: h('b', {style: 'color: black'}, msg),
				})
			})
		},
		stopPatient(t) {
			if (t === 1) {
				this.is_stop_1 = true;
			} else {
				this.is_stop_2 = true;
			}
			this.$API['doctor.bench'].ring_off.post({
				patient_sn: this.patient_sn,
				type: t,
			}).then((res) => {
				console.log('Res:ring_off', res);
				this.is_stop_1 = false;
				this.is_stop_2 = false;
				this.ring_off = false;
				this.stat = 0;

				if (res.code !== 0) {
					this.mute(true);
					if (res.code === 2) {
						ElNotification({
							title: '提示',
							message: h('b', {style: 'color: black'}, res.msg),
						});
						this.patient_id = 0;
						this.patient_sn = '';
						this.ringOff();
						this.loadDoctorInfo();
					} else this.$alert(res.message, "提示", {type: 'error'});
				} else {
					if (t === 1 && res.data.channel) {
						this.stat = 1;
						this.patient_id = res.data.patient_id;
						this.patient_sn = res.data.patient_sn;
						this.removeFromPatientOrderList(res.data.patient_sn);
						// this.startTime();
						this.loadPatientOrder();
						// this.$nextTick(() => {
						// 	let channel = res.data.channel;
						// 	this.rtc_obj.init();
						// 	this.rtc_obj.setChannel(channel, this.rtc_ui);
						// });
					} else {
						this.mute(true);
					}
					this.loadDoctorInfo();
				}
			}).catch((msg) => {
				this.is_stop_1 = false;
				this.is_stop_2 = false;
				this.mute(true);
				ElNotification({
					title: '提示',
					message: h('b', {style: 'color: black'}, msg),
				})
			})
		},
		appendToPatientOrder(patient_sn) {
			let filter = this.patient_order_list.filter(item => item.patient_sn === patient_sn);
			if (filter.length > 0) return;

			this.$API['patient.patient_order'].detail.post({patient_sn: patient_sn}).then((res) => {
				console.log('Res:patient order detail', res);
				if (res.code !== 0) {
					ElNotification({
						title: '提示',
						message: h('b', {style: 'color: black'}, res.message),
					})
				} else {
					this.patient_order_list.push(res.data);
				}
			}).catch((msg) => {
				ElNotification({
					title: '提示',
					message: h('b', {style: 'color: black'}, msg),
				})
			})
		},
		removeFromPatientOrderList(patient_sn) {
			let i = this.patient_order_list.findIndex(item => item.patient_sn === patient_sn);
			if (i > -1) {
				this.patient_order_list = this.patient_order_list.filter(item => item.patient_sn !== patient_sn);
			}
		},
		noSignal() {
			/*if (!this.last_sig || Math.abs(this.last_sig - new Date().getTime()) > 100) {
				this.$alert('请联系患者继续完成后续访问', "视频通话被异常挂断", {type: 'error'});
				this.last_sig = new Date().getTime();
			}*/
		},
		save() {
			if (!this.patient_sn) {
				return;
			}
			this.isSaveing = true;
			if (this.actionName === 'first') { // 病例
				this.$API['patient.patient_order'].caseStore.post({
					patient_sn: this.patient_sn,
					principal_action: this.principal_action,
					medical_history: this.medical_history,
					anamnesis: this.anamnesis,
					allergy: this.allergy,
					pseudodiagnosis: this.pseudodiagnosis,
					patient_suggest: this.patient_suggest,
				}).then((res) => {
					this.isSaveing = false;
					if (res.code !== 0) {
						this.$alert('save:' + res.message, "提示", {type: 'error'});
					} else {
						this.$message.success("操作成功")
					}
				}).catch((msg) => {
					this.isSaveing = false;
					this.$alert(msg, "提示", {type: 'error'})
				})
			} else { // 用药建议
				if (this.medicine_advise.length === 0) {
					this.$alert('请添加药品', "提示", {type: 'error'});
					return;
				}
				let medical_list = tool.crypto.BASE64.encrypt(JSON.stringify(this.medicine_advise));
				this.$API['patient.patient_order'].medicineStore.post({
					patient_sn: this.patient_sn,
					medical_list
				}).then((res) => {
					this.isSaveing = false;
					if (res.code !== 0) {
						this.$alert('save:' + res.message, "提示", {type: 'error'});
					} else {
						this.$message.success("操作成功")
					}
				}).catch((msg) => {
					this.isSaveing = false;
					this.$alert(msg, "提示", {type: 'error'})
				})
			}
		},
		autoUp () {
			this.centerDialogVisible = false;
			location.reload();
		},
		startQuery () {
			if (this.queryIntr) {
				clearInterval(this.queryIntr);
			}
			this.queryIntr = setInterval(() => {
				this.$API['doctor.bench'].status.post({}).then((res) => {
					console.log('Res:status:startQuery', res);
					if (res.code !== 0) {
						this.$alert('startQuery:' + res.message, "提示", {type: 'error'});
					} else {
						let doctor_info = res.data;
						if (doctor_info.online != 1) {
							this.centerDialogVisible = true;
							clearInterval(this.queryIntr);
						}
					}
				});
			}, 1000 * 60);
		},
		startPing () {
			if (this.pingIntr) {
				clearInterval(this.pingIntr);
			}
			this.pingIntr = setInterval(() => {
				if (this.ws.bufferedAmount === 0) {
					this.ws.send(JSON.stringify({ mode: 'ping' }));
				}
			}, 1000);
		},
		loadPatientPic(patient_sn) {
			if(!patient_sn){
				return false;
			}
			let that = this;
			that.patient_pic_list = [];
			that.patient_pic = '';
			this.$API['patient.patient_order'].patientPic.post({patient_sn: patient_sn}).then((res) => {
				if (res.code !== 0) {
					ElNotification({
						title: '提示',
						message: h('b', {style: 'color: black'}, res.msg),
					})
				} else {
					let pic_data_list = [];
					res.data.forEach(item => {
						pic_data_list.push(item.patient_pic_url);
					})
					if (pic_data_list.length > 0){
						that.patient_pic_list = pic_data_list;
						that.patient_pic = pic_data_list[pic_data_list.length - 1];
					}
				}
			}).catch((msg) => {
				ElNotification({
					title: '提示',
					message: h('b', {style: 'color: black'}, msg),
				})
			})
		},
		switchPic(index){
			this.patient_pic_index = index;
		},
		showPic(){
			this.patient_pic_index = this.patient_pic_list.length;
			this.show_patient_pic_num = true;
		},
		closePic(){
			this.show_patient_pic_num = false;
		}
	}
}
</script>

<style>
.doctor-style {
	width: 200px;
	z-index: 20;
	min-height: 150px;
}
</style>

<style scoped>
.waiting-users {
	width: 100%;
}

.box-card {
	border-style: solid;
	border-color: #e4e7ed;
	border-width: 0 0 1px 0;
	box-shadow: none;
	border-radius: 0;
	margin-bottom: 0;
	padding: 24px 0;
}

.waiting-users .list {
	width: 100%;
	padding: 0;
}

.waiting-users .list > div {
	padding: 0 24px;
}

.waiting-users .list > div:hover {
	background-color: #ECF1F3;
}

.bench-body { /*width: 458px; */
	width: 100%;
}

.bench-main {
	flex: 1;
	justify-content: center;
	align-items: center;
}

.bench-content {
	padding: 15px;
	align-items: center;
	justify-content: center;
}

.bench-bott {
	width: 100%;
	justify-content: center;
}

.bench-bott .answer {
	display: flex;
	flex-direction: column;
	flex: 0;
}

.user-num {
	width: 28px;
	height: 28px;
	border-radius: 50%;
	border: 1px solid #e4e7ed;
	display: flex;
	justify-content: center;
	align-items: center;
}

.user-row {
	align-items: center;
	width: 100%;
}

.bench-stat {
	display: flex;
	align-items: center;
	justify-content: flex-start;
	margin-top: 10px;
}

.bench-stat .text1 {
	color: #999;
	font-weight: 400;
	margin-right: 10px;
}

.bench-stat .text2 {
	color: #FF2A23;
	font-weight: 400;
	font-size: 12px;
}

.bench-stat .text2.dark {
	color: #333;
}

.bench-stat .text0 {
	color: #222;
	font-weight: 500;
	margin-right: 10px;
}

.side-head {
	height: auto;
	display: block;
	width: 100%;
	padding-top: 24px;
	padding-bottom: 24px;
}

.user-row .name {
	margin-right: 15px;
}

.user-row .user-met {
	align-items: center;
	display: flex;
}

.user-row .sex {
	margin-right: 8px;
	display: inline-block;
}

.user-row .sex::after {
	content: ' ';
	width: 1px;
	height: 11px;
	background: #666;
	display: inline-block;
	margin-left: 8px;
}

.user-row .sex-icon {
	margin-right: 10px;
}

.bench-side {
	padding: 24px;
	flex-direction: column;
}

.bench-side-user {
	border: 1px solid #DDDDDD;
	border-radius: 4px;
}

.bench-side-user header {
	background-color: #F7F7F7;
	height: 123px;
	display: flex;
	justify-content: space-around;
	width: 100%;
	border-bottom: 1px solid #ddd;
	flex-direction: column;
	padding: 16px 0 16px 16px;
}

.bench-side-user header .head-item {
	color: #333;
	font-size: 14px;
	font-weight: 500;
	margin-bottom: 6px;
}

.bench-side-user-dec {
	flex-direction: column;
	height: auto;
	padding-bottom: 16px;
}

.head-table {
}

.head-table .head-label {
	width: 70px;
	flex: 0 70px;
	text-align: right;
	margin-top: 16px;
	line-height: 20px;
}

.head-table .head-con {
	padding: 16px;
	flex: 1;
	line-height: 20px;
}

.sticky-top {
	position: sticky;
	top: 0;
	z-index: 100;
}

.save-row {
	height: 90px;
	border-top: 1px solid #ddd;
	bottom: 0;
	z-index: 100;
	background-color: #fff;
	display: flex;
	justify-content: center;
	align-items: center;
	position: fixed;
	width: 460px;
}

.save-row button {
	min-width: 172px;
}

.bench-side-action, .side-tabs, .side-tabs table {
	width: 100%;
}

.side-tabs table {
	border-spacing: 10px;
}

.side-tabs table tr {
	margin-bottom: 10px;
}

.save-row-height, .save-row {
	height: 120px;
}

.advise-head {
	display: flex;
	align-items: center;
	margin-bottom: 16px;
}

.advise-head button {
	margin-left: 10px;
}

.advise-body {
	width: calc(100% - 10px);
}

.advise-body-item {
	margin-bottom: 16px;
	background-color: #F7F7F7;
	height: 128px;
	position: relative;
	display: flex;
	flex-direction: column;
	padding: 16px;
}

.advise-body-item .del-act {
	position: absolute;
	top: -5px;
	right: -5px;
}

.advise-body-in {
	display: flex;
	flex-direction: row;
	align-items: center;
	height: 30px;
	margin-bottom: 16px;
}

.advise-body-in .advise-body-in-head {
	color: #333;
	font-weight: 500;
	flex: 1;
}

.advise-body-in .advise-body-inp {
	height: 26px;
	flex-basis: 120px;
}

.advise-body-in .advise-med {
	margin-right: 5px;
	flex-basis: 128px;
}

.advise-body-desc {
}

.advise-body-desc textarea {
}

.bench-main .video {
	border: 1px solid #ddd;
	width: 100%;
}

.bench-main .video video {
	width: 100%;
	max-height: 50vh;
}

.bench-bott .video-act {
	display: flex;
	justify-content: space-between;
	width: 100%;
}

.bench-main .video.ringOff {
	border: none;
}

.ring-off-text {
	display: flex;
	flex-direction: column;
}

.ring-off-text:first-child {
	margin-bottom: 10px;
}


.demo-image__error .image-slot {
	font-size: 30px;
}
.demo-image__error .image-slot .el-icon {
	font-size: 30px;
}
.demo-image__error .el-image {
	width: 100%;
	height: 200px;
}
.bench-main {
	position: relative;
}
.bench-doctorVideoWrap {
	position: absolute;
	top: 30px;
	right: 30px;
}

.image-preview {
	position: relative;
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	text-align: center;
	/* 根据你的需要调整以下样式 */
	width: 100%;
	height: 100%;
}

.image-info {
	position: fixed;
	right: 25px; /* 距离页面右边的间距 */
	bottom: 300px; /* 距离页面底部的间距 */
	background-color: rgba(0, 0, 0, 0.5); /* 半透明背景 */
	color: #fff; /* 文字颜色 */
	padding: 5px 10px; /* 内边距 */
	border-radius: 4px; /* 圆角 */
	z-index: 9999; /* 确保内容显示在其他元素之上 */
}
</style>
